package com.qf.Controller;

import com.qf.Util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*2021/10/09*/public class BaseController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /*
        页面请求对应模块的时候，传递对应的方法名，执行方法即可
         */
        //1.获取自身的类对象
        Class self = this.getClass();
        String method = req.getParameter("method");

        try {
            //2.根据类对象获取对应的方法
            Method method1 = self.getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            //3.执行该方法
            String invoke = (String)method1.invoke(this, req, resp);

            //4.统一处理结果
            if(invoke!=null){//转发
                if(invoke.startsWith(Constants.FORWARD)){
                    String path=invoke.substring(invoke.indexOf(":")+1);
                    req.getRequestDispatcher(path).forward(req, resp);
                }else if(invoke.startsWith(Constants.REDIRECT)){//重定向
                    String path=invoke.substring(invoke.indexOf(":")+1);
                    resp.sendRedirect(req.getContextPath()+path);

                }else {//相应一个结果，JSON，数字，字符串
                    resp.getWriter().println(invoke);
                }
            }
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }


}
